// 云函数入口文件
const cloud = require('wx-server-sdk')
const superagent = require('superagent')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.getyzm) { //获取验证码
    let jub = await db.collection('user').where({
      id: wxContext.OPENID
    }).get()

    if (jub.data.length) {
      return "ok"
    } else {
      const url = `http://8.129.187.205:3000/wyu/jwxc/login`

      let data = await superagent
        .get(url)
        .then()

      let arr = data.text.slice(9, -2)
      return {
        data: arr
      }
    }

  } else if (event.yzmValue) { //输入验证码
    const url_1 = `http://8.129.187.205:3000/wyu/jwxc/yzm`

    if (event.xhValue) { //第一次登陆
      let data_login = await superagent
        .get(url_1)
        .query({
          yzm: event.yzmValue,
          xh: event.xhValue,
          mm: event.mmValue
        })
        .then()

      let status = JSON.parse(data_login.text).stauts
      if (typeof status == "string") { //登陆失败
        return status
      } else { //登陆成功
        await db.collection('user').add({
          data: {
            xh: event.xhValue,
            mm: event.mmValue,
            id: wxContext.OPENID
          }
        }).then()
        return status
      }
    } else { //不是第一次登陆
      let data = await db.collection('user')
        .where({
          id: wxContext.OPENID
        }).get()

      let data_login = await superagent
        .get(url_1)
        .query({
          yzm: event.yzmValue,
          xh: data.data[0].xh,
          mm: data.data[0].mm
        })
        .then()
      return JSON.parse(data_login.text).stauts
    } //else-2

  } else if (event.skyw) {
    const url = `http://8.129.187.205:3000/wyu/jwxc/login`

    let data = await superagent
      .get(url)
      .then()

    let arr = data.text.slice(9, -2)
    return {
      data: arr
    }
  }

}